<template>
  <div class="container" ref="mainCon">
    <el-row
      class="toolbar searchInputWidth"
      style="padding-bottom: 0; padding-top: 24px !important"
    >
      <el-form :inline="true" :model="filterField" ref="searchConditions">
        <el-col :lg="8" :xl="6">
          <el-form-item label="接件单位" class="row-padding-bottom">
            <el-input
              v-model="filterField.receiveUnit"
              placeholder="请输入接件单位"
              clearable
            ></el-input>
            <!-- <el-select
              placeholder="请选择接件单位"
              clearable
              v-model="filterField.companyName"
            >
              <el-option
                v-for="item in jobStatusOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :lg="8" :xl="6">
          <el-form-item label="接件日期" class="row-padding-bottom">
            <timeSelection
              @getStartTimeValue="getStartTimeValue"
              @getEndTimeValue="getEndTimeValue"
            ></timeSelection>
          </el-form-item>
        </el-col>
        <el-col :lg="8" :xl="6">
          <el-form-item label="">
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <!-- <el-button type="primary" class="createSalaryBut"  @click="downLoadFile()">导出</el-button> -->
          </el-form-item>
          <el-form-item>
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaochu"
              v-sdc
              @click="exportList"
            >
              <span class="opetareText">导出</span>
            </el-button>
            <!-- <exportBtn :dataLen="tableList.length" :filterField="filterField" api="api-r/complaintStatsHandler/export"></exportBtn> -->
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <div class="spacing"></div>
    <div
      ref="tableBox"
      :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
    >
      <el-table
        ref="tableBox1"
        :max-height="tableHeight"
        :data="tableList"
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        style="border: 1px solid #dfe6ec"
        border
        row-key="id"
        lazy
        :load="loadChildren"
        :tree-props="{
          children: 'industryDataList',
          hasChildren: 'hasChildren',
        }"
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column prop="companyName" label="接件单位" width="230">
        </el-table-column>
        <el-table-column
          prop="industryName"
          label="所属行业"
          :formatter="formatTd"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="caseTotal"
          label="件数（件）"
          :formatter="formatTd"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="toDoTotal"
          label="待办件（件）"
          align="center"
          :formatter="formatTd"
        >
        </el-table-column>
        <el-table-column
          prop="acceptedTotal"
          label="办结件（件）"
          :formatter="formatTd"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="涉及人数（人）"
          width="180"
          align="center"
          prop="peopleTotal"
          :formatter="formatTd"
        >
        </el-table-column>
        <el-table-column
          prop="moneyTotal"
          label="金额（元）"
          align="center"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column label="操作" align="left" fixed="right" width="110">
          <template slot-scope="scope">
            <el-link type="primary" @click="toDetail(scope.$index, scope.row)"
              >查看</el-link
            >
          </template>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isShow">
          <emptyTable emptyText="暂无相关信息"></emptyTable>
        </div>
      </el-table>
      <Pagination
        ref="pagination"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
        v-show="false"
      ></Pagination>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
export default {
  name: 'caseRegister', //昆明案件导入-案件登记
  data() {
    return {
      //表格数据
      tableList: [],
      requestUrl: 'api-r/complaintStatsHandler/complaintStats',
      areaId: '',
      //搜索条件
      filterField: {
        receiveUnit: '', //接件单位
        startDate: '', //开始时间
        endDate: '', //结束时间
      },
      isShow: false,
      loading: true, //列表加载
      tableHeight: null,
      hiddleToolBar: false,
      jobStatusOptions: [],
    }
  },
  created() {
    this.$nextTick(function () {
      // this.$refs.pagination.getTableListData();
      this.searchList()
    })
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      // this.$refs.pagination.getTableListData();
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  methods: {
    /**
     * @description: 获取开始日期
     * @param {*} urls
     * @param {*} datas
     */
    getStartTimeValue(val) {
      if (val) {
        this.filterField.startDate = val
      } else {
        this.filterField.startDate = ''
      }
    },
    /**
     * @description: 获取结束日期
     * @param {*} urls
     * @param {*} datas
     */
    getEndTimeValue(val) {
      if (val) {
        this.filterField.endDate = val
      } else {
        this.filterField.endDate = ''
      }
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.axios.post(this.requestUrl, this.filterField).then((res) => {
        if (!res.data.hasError) {
          if (res.data.result && res.data.result.length > 0) {
            res.data.result.forEach((item, index) => {
              item.id = index + 1
              if (item.caseTotal > 0) {
                item.hasChildren = true
                // item.industryDataList.forEach((each, i) => {
                //   each.id = index + "" + i;
                // })
              } else {
                item.hasChildren = false
                // item.industryDataList = []
              }
            })
            // res.data.result.splice(-1,1);
            this.tableList = res.data.result
            if (this.tableList.length < 1) {
              this.isShow = true
            }
            console.log(this.tableList)
          } else {
            this.tableList = []
          }
          this.loading = false
          if (this.tableList.length < 1) {
            this.isShow = true
          }
        } else {
          this.$message({
            type: 'warning',
            message: res.data.errorMsg,
          })
        }
      })
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 230

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    // 查看详情
    toDetail(index, row) {
      var query = {
        activeName: '1',
        currentTabComponent: 'caseRegistration',
        receiveUnit: row.companyName == '-' ? '' : row.companyName,
      }

      this.$router.push({
        path: '/home/kMCaseComplaint/otherComplaintsTab',
        name: 'otherComplaintsTab',
        query: query,
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/kMCaseComplaint/otherComplaintsTab',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    exportList() {
      if (this.tableList.length > 0) {
        window.location.href =
          common.commonApi +
          'api-r/complaintStatsHandler/export?startDate=' +
          this.filterField.startDate +
          '&endDate=' +
          this.filterField.endDate +
          '&receiveUnit=' +
          this.filterField.receiveUnit +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        this.$message({
          type: 'warning',
          message: '无数据导出',
        })
      }
    },
    loadChildren(tree, treeNode, resolve) {
      console.log(tree)
      var data = {
        receiveUnit: tree.companyName,
        level: 'second',
      }
      console.log(data)
      // data = Object.assign(data, this.filterField);
      this.axios.post(this.requestUrl, data).then((res) => {
        if (!res.data.hasError) {
          if (res.data.result) {
            var data = res.data.result
            data.forEach((item, index) => {
              item.id = index + 'second'
              // item.hierarchyText = item.hierarchy;
              // item.receiveUnitText = item.receiveUnit;
              // item.total = item.overNum + item.doingNum;
              // if (tree.receiveUnit) {
              //   item.hasChildren = false;
              //   item.hierarchy = "";
              //   item.receiveUnit = "";
              // } else {
              //   item.hierarchy = "";
              //   if (item.total > 0) {
              //     item.hasChildren = true;
              //   } else {
              //     item.hasChildren = false;
              //   }
              // }
            })
            resolve(data)
          } else {
            this.tableList = []
          }
          this.loading = false
          if (this.tableList.length < 1) {
            this.isShow = true
          }
        } else {
          this.$message({
            type: 'warning',
            message: res.data.errorMsg,
          })
        }
      })
    },
    // 总计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        if (index === 1) {
          sums[index] = ' '
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sums[index]
        } else {
          sums[index] = ' '
        }
      })
      return sums
    },
  },
}
</script>

<style scoped lang="less">
.container {
  // padding:24px;
  .uploadBox {
    position: relative;
    .uploadImg {
      width: 96px;
      height: 36px;
      padding: 0px;
      color: #009588;
      border: 1px solid #009588;
      cursor: pointer;
    }
    .upLoadDom {
      position: absolute;
      width: 96px;
      height: 36px;
      top: 0;
      left: 0;
      opacity: 0;
      line-height: 0px;
      form {
        input {
          width: 96px;
          height: 36px;
          line-height: 0px;
          cursor: pointer;
        }
      }
    }
  }
}
.topTitle {
  height: 67px;
  background-color: #e4ebf1;
  padding-left: 24px;
  // font: bold 18px/67px Microsoft YaHei;
}
.mainCon {
  top: 198px;
}
.createSalaryBut {
  background: #009588;
  border: 1px solid #009588;
  padding: 10px 23px;
  margin-left: 12px;
  &:hover {
    opacity: 0.8;
  }
}
@media only screen and (max-width: 1366px) {
  /deep/.searchInputWidth .el-form--inline .el-form-item__label {
    width: 80px;
  }
}
@import '../../../static/css/filterArea.less';
</style>
